<?php

namespace App\Models;


use App\Http\Common\Lib\Common;

class League extends BaseModel
{
	protected $validatorName = 'League';

	/**
	 * 通过名字获取联赛实例
	 * @param $name
	 * @return mixed
	 */
	public static function getByName($name)
	{
		return League::firstOrCreate(['name' => $name]);
	}

	public function add($input)
	{
		$validateRes = $this->validateData($input, 'add');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('name', $input['name'], [['status', '>', -1]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该联赛已存在');
		}
		$league = new League();
		$league->setData($input);
		$res = $league->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), [$this->primaryKey => $league->id]);
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	public function edit($input)
	{
		$validateRes = $this->validateData($input, 'edit');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('name', $input['name'], [['status', '>', -1], [$this->primaryKey, '<>', $input[$this->primaryKey]]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该联赛已存在');
		}
		$league = $this->where($this->primaryKey, $input[$this->primaryKey])->where('status', '>', -1)->first();
		if (!$league) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		unset($input['$this->primaryKey']);
		$league->setData($input);
		$res = $league->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}
}
